<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input
        type="text"
        v-model.trim="stuMsg.name"
      />
    </div>
    <div>
      <span>年龄:</span>
      <input
        type="number"
        v-model.number="stuMsg.age"
      />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="stuMsg.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="updataFn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr
          v-for="(obj, index) in studentList"
          :key="index"
        >
          <td>{{ index+1 }}</td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="delStu(index)">删除</button>
            <button @click="showMsg(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
export default {
  data() {
    return {
      stuMsg: {
        name: '',
        age: '',
        sex: ''
      },
      flag: -1
    }
  },
  methods: {
    // 删除
    ...mapMutations(['delStu']),
    updataFn() {
      if (!this.stuMsg.name.length || !this.stuMsg.age > 0 || !this.stuMsg.sex)
        return alert('输入内容不合法，请检查！')
      console.log()
      if (this.flag < 0) {
        this.$store.commit('addStu', { ...this.stuMsg })
      } else {
        this.studentList.splice(this.flag, 1, { ...this.stuMsg })
        this.flag = -1
      }
    },
    showMsg(index) {
      this.stuMsg.name = this.studentList[index].name
      this.stuMsg.age = this.studentList[index].age
      this.stuMsg.sex = this.studentList[index].sex
      this.flag = index
    }
  },
  computed: {
    // 学生列表
    ...mapState(['studentList'])
  }
}
</script>
